//
//  JCLMainViewController.swift
//  WeiBo
//
//  Created by DDC on 2017/9/6.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit
import pop
class JCLMainViewController: UITabBarController {
    
    
    /// 定时器
    fileprivate var timer : Timer?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUpChildControllers()
        setUpComposeButton()
        setUpTimer()
        setUpNewfeatureWelcomeView()
        //测试未读数量
        JCLNetWorkTools.shared.unreadCount { (count) in
            print("刷新到\(count)条新数据")
        
        }
        
        delegate = self
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogon), name: NSNotification.Name(rawValue: JCLUserShouldLoginNotification), object: nil)
    }
    /// 销毁定时器
    deinit {
        timer?.invalidate()
        //移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
    //通知方法
    @objc fileprivate func userLogon (n: Notification) {
        print("\(n)")
        
        let nav = UINavigationController(rootViewController: JCLOAuthViewController())
        present(nav, animated: true, completion: nil)
    }
    // MARK:  - 懒加载
   fileprivate lazy var composeButton = UIButton.hm_button(withImageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
    // MARK:  - 按钮点击事件实现
    @objc fileprivate func composeButtonClick (){
        print("compseButton")
        
        let v = JCLComposeView.composeView()
        // 显示撰写界面
        v.show {[weak v] (clsName) in
            
        /// 字符串转换所需要的控制器
            guard let clsName = clsName,
            let cls = NSClassFromString(Bundle.main.namespace() + "." + clsName) as? UIViewController.Type
            else {
                v?.removeFromSuperview()
                return
            }
            // 实例化控制器
            let vc = cls.init()
            let nav = UINavigationController(rootViewController: vc)
            // 在界面加载之前--强行更新约束
            nav.view.layoutIfNeeded()
            // modal
            self.present(nav, animated: true, completion: {
                v?.removeFromSuperview()
            })
         }
        
    }
    
    // MARK:  - 支持横竖方法  
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask
        {
        return .portrait
    }

}

// MARK: - 新特性界面
extension JCLMainViewController {
    
    /// 设置新特性界面
    fileprivate func setUpNewfeatureWelcomeView () {
    
        let v = isNewVersion ? JCLNewfeatureView.newfeatureView() : JCLWelcomeView.welCome()
      
        view.addSubview(v)
    }
    
    fileprivate var isNewVersion:Bool {
        //判断是否新版版逻辑
        // 1.取出当前版本号
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
        // 2.取保存在Document中[iTunes备份](存储在偏好中)的版本号
        let filePath:String = ((NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last as NSString?)?.appendingPathComponent("versionNumber"))!
        let systemVersion = (try? String.init(contentsOfFile: filePath)) ?? ""
        // 3.保存当前版本号到偏好中
        try? currentVersion?.write(toFile: filePath, atomically: true, encoding: .utf8)
        // 4.返回两个版本号是否一致
        return currentVersion != systemVersion
    }
    
}
// MARK: - UITabBarControllerDelegate
extension JCLMainViewController :UITabBarControllerDelegate {
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        print("\(viewController)")
        
        //获取点击控制器索引
        let idx = childViewControllers.index(of: viewController)
        
        if selectedIndex == 0 && idx == selectedIndex {
            print("首页")
            
            //滚动视图到顶部
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! JCLHomeViewController
            //设置滚动的位置
            vc.tableView?.setContentOffset(CGPoint(x:0,y:-64), animated: true)
            
            //新添一条线程刷新数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                
                vc.loadData()
            })
            
        }
        
        return !viewController .isMember(of: UIViewController.self)
        
    }
}

// MARK: - tabbar 显示未读数量badge
extension JCLMainViewController {
    
    fileprivate func setUpTimer () {
        
        //如果没有登录 不开启定时器
        if !JCLNetWorkTools.shared.userLogon {
             return
        }
        //开启定时器
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(loadUnreadCount), userInfo: nil, repeats: true)
    }
    
    /// 定时器执行方法
    @objc fileprivate func loadUnreadCount () {
        
        JCLNetWorkTools.shared.unreadCount { (count) in
            
            let item = self.tabBar.items?[0]
            item?.badgeValue = count > 0 ? "\(count)" : nil
            
            //设置app的badge显示
            UIApplication.shared.applicationIconBadgeNumber = count
            
        }
    }
    
}
    // MARK:  - Extension
extension JCLMainViewController{
    
    // MARK:  - 设置按钮
    fileprivate func setUpComposeButton() {
        
        //添加按钮
        tabBar.addSubview(composeButton)
        //设置frame
        let count = CGFloat( childViewControllers.count)
        let w = tabBar.bounds.width / count
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        // MARK:  - 按钮点击事件
        composeButton.addTarget(self, action: #selector(composeButtonClick), for: .touchUpInside)
    }
    
    // MARK:  - 设置子控制器
     fileprivate func setUpChildControllers() {
        
        
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        
        //拼接文件名
        let jsonPath = (docDir as NSString).appendingPathComponent("data.json")
        
        var data = NSData(contentsOfFile: jsonPath)
        
        if data == nil {
            
            let filePath = Bundle.main.path(forResource: "data.json", ofType: nil)
            data = NSData(contentsOfFile: filePath!)
        }
        
        //从json获取数据并转化为数组
       guard  let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:Any]]
        else {
            return
        }
        
        
        //创建各个控制器所需数组
/*      let array :[[String:Any]] = [
    ["clsName":"JCLHomeViewController","title":"首页","imgName":"tabbar_home",
     "visitorInfo":["imageName":"","message":"关注一些人，回这里看看有什么惊喜"]
        
            ],
    ["clsName":"JCLMessageViewController","title":"消息","imgName":"tabbar_message_center",
     "visitorInfo":["imageName":"visitordiscover_image_message","message":"登录后，别人评论你的微博，转发你的消息，都会在这里看到"]
     ],
    ["clsName":"UIViewController"],//模仿中间按钮空白区域
    ["clsName":"JCLDiscoveryViewController","title":"发现","imgName":"tabbar_discover",
     "visitorInfo":["imageName":"visitordiscover_image_message","message":"登录后,最新、最热信息尽在掌握"]
     ],
 ["clsName":"JCLProfileViewController","title":"我","imgName":"tabbar_profile",
  "visitorInfo":["imageName":"visitordiscover_image_profile","message":"登录后，你的个人信息会展示在这里，不会让别人看到哦"]
  ]]
        将数组数据保存为json格式
        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        (data as NSData).write(toFile: "/Users/DDC/Desktop/data.json", atomically: true)
        
*/
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        viewControllers = arrayM
    
    }
    // MARK:  - 创建控制器
    func controller(dict:[String : Any]) -> UIViewController{
        guard let clsName = dict["clsName"] as? String,
             let title = dict["title"] as? String,
             let imgName = dict["imgName"] as? String,
             let cls = NSClassFromString(Bundle.main.namespace() + "." + clsName)as? JCLBaseViewController.Type,
             let visitorDict = dict["visitorInfo"] as? [String :String]
        
            else {
                
                return UIViewController()
        }
        
        let vc = cls.init()
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imgName)
        vc.tabBarItem.selectedImage = UIImage(named: imgName + "_highlighted")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        vc.visitorInfoDictionary = visitorDict

//        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:[UIFont .systemFont(ofSize: 14)]], for:UIControlState(rawValue: 0))
        
        let nav = JCLNavigationController(rootViewController: vc)
        
        return nav
    }
    
}


